package com.wlps.handler;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.wlps.contant.Contant;
import com.wlps.entity.SysPermission;
import com.wlps.entity.SysUser;
import com.wlps.result.ResultUtils;
import com.wlps.service.ISysPermissionService;
import com.wlps.service.ISysUserService;
import com.wlps.utils.JwtUtils;
import com.wlps.vo.MenuVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component("loginSuccessHandler")
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ISysPermissionService permissionService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        //生成token
        ServletOutputStream out = httpServletResponse.getOutputStream();
        SysUser user = (SysUser) authentication.getPrincipal();
        String token = jwtUtils.generateToken(user);
//        redisTemplate.opsForValue().set(Contant.USERDETAILS_KEY+user.getUsername(),user);
        redisTemplate.opsForValue().set(Contant.TOKEN_KEY + token, user.getId(),50,TimeUnit.MINUTES);
        redisTemplate.opsForValue().set(Contant.TOKEN_ID_KEY + user.getId().toString(), token,50,TimeUnit.MINUTES);
        MenuVo vo = new MenuVo();
        vo.setToken(token);
        vo.setRoleName(permissionService.roleFindByUserId(user.getId()));
        vo.setUserId(user.getId());
//3.查询用户菜单权限
        List<SysPermission> permissionList = user.getPermissionList();
        if (permissionList.size() > 0) {
//设置用户拥有的权限字段
            List<String> auth = permissionList.stream().filter(item -> item !=
                    null).map(item -> item.getCode()).collect(Collectors.toList());
            vo.setAuthList(auth);
//获取除按钮以外的菜单
            List<SysPermission> collect = permissionList.stream().filter(item -> item !=
                    null && !item.getType().equals("2")).collect(Collectors.toList());
            List<SysPermission> routerList = permissionList.stream().filter(item -> item
                    != null && item.getType().equals(1)).collect(Collectors.toList());
//            List<SysPermission> routerList = permissionList;
            vo.setRouterList(routerList);
            System.out.println(routerList);
//生成菜单树数据
            List<SysPermission> listMenu = makeTree(collect, 0L);
            vo.setMenuList(listMenu);
//获取路由数据
//            permissionList = user.getPermissionList();
//            List<SysPermission> routerList = permissionList.stream().filter(item -> item
//                    != null && !"0".equals(item.getType())).collect(Collectors.toList());
////            List<SysPermission> routerList = permissionList;
//            vo.setRouterList(routerList);
//            System.out.println(routerList);
        }
        redisTemplate.opsForValue().increment(Contant.ONLINEUSER_KEY);
        String str = JSONObject.toJSONString(ResultUtils.success("认证成功", vo), SerializerFeature.DisableCircularReferenceDetect);
        out.write(str.getBytes("UTF-8"));
        out.flush();
        out.close();
    }

    /**
     * 组装树
     *
     * @param menuList
     * @param pId
     * @return
     */
    private static List<SysPermission> makeTree(List<SysPermission> menuList, Long pId) {
//子类
        List<SysPermission> children = menuList.stream().filter(x -> x.getParentId() ==
                pId).collect(Collectors.toList());
//后辈中的非子类
        List<SysPermission> successor = menuList.stream().filter(x -> x.getParentId() !=
                pId).collect(Collectors.toList());
        if (children.size() > 0) {
            children.forEach(x ->
                    {
                        if (successor.size() > 0) {
                            makeTree(successor, x.getId()).forEach(
                                    y -> x.getChildren().add(y)
                            );
                        }
                    }
            );
        }
        return children;
    }
}